package com.guosen.zebra.gateway.route.parser;

import com.guosen.zebra.gateway.route.model.SubUrlMethodMapping;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 子URL和方法映射配置解析器
 */
public final class SubUrlMethodMappingParser {
    private static final Logger LOGGER = LoggerFactory.getLogger(SubUrlMethodMappingParser.class);

    /**
     * 换行
     */
    private static final String LF = "\n";

    /**
     * 映射标识符
     */
    private static final String MAP_FLAG = "->";

    /**
     * 子URL索引
     */
    private static final int SUB_URL_INDEX = 0;

    /**
     * 方法名索引
     */
    private static final int METHOD_NAME_INDEX = 1;

    /**
     * 每个配置项的元素个数
     */
    private static final int ITEM_SIZE = 2;

    private SubUrlMethodMappingParser(){}

    /**
     * 解析
     * @param subUrlMethodMappingCfgStr 子URL和方法映射配置字符串
     * @return 子URL和方法映射列表
     */
    public static List<SubUrlMethodMapping> parse(String subUrlMethodMappingCfgStr) {
        List<SubUrlMethodMapping> subUrlMethodMappings = new ArrayList<>();
        if (StringUtils.isBlank(subUrlMethodMappingCfgStr)) {
            return subUrlMethodMappings;
        }

        String[] subUrlMethodMappingCfgItems = subUrlMethodMappingCfgStr.split(LF);
        for (String subUrlMethodMappingCfgItem : subUrlMethodMappingCfgItems) {
            SubUrlMethodMapping subUrlMethodMapping = toSubUrlMethodMapping(subUrlMethodMappingCfgItem);
            if (subUrlMethodMapping == null) {
                continue;
            }

            subUrlMethodMappings.add(subUrlMethodMapping);
        }

        return subUrlMethodMappings;
    }

    private static SubUrlMethodMapping toSubUrlMethodMapping(String subUrlMethodMappingCfgItem) {
        String[] itemElements = subUrlMethodMappingCfgItem.split(MAP_FLAG);
        if (itemElements.length != ITEM_SIZE) {
            LOGGER.error("Invalid sub URL method mapping configuration {}", subUrlMethodMappingCfgItem);
            return null;
        }

        String subUrl = itemElements[SUB_URL_INDEX];
        String methodName = itemElements[METHOD_NAME_INDEX];

        SubUrlMethodMapping subUrlMethodMapping = new SubUrlMethodMapping();
        subUrlMethodMapping.setSubUrl(subUrl);
        subUrlMethodMapping.setMethod(methodName);

        return subUrlMethodMapping;
    }
}
